package com.codedef.diaryserver.controller;

import com.codedef.diaryserver.domain.DiaryDao;
import com.codedef.diaryserver.service.DiaryService;
import com.codedef.diaryserver.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/diary")
public class DiaryController {

    @Autowired
    DiaryService diaryService;

    @Autowired
    private UserService userService;

    private static final Logger LOG = LoggerFactory.getLogger(DiaryController.class);
    //Logger LOG = LoggerFactory.getLogger(DiaryController.class);

    /*
    @GetMapping("/")
    public String getDiaryRoot() {
        System.out.println("进入DiaryController.getDiaryRoot");
        return "root";
    } */

    @GetMapping("")
    public List<DiaryDao> getDiaryList() {
        // 验证用户登录
//        Integer sessionUserId = userService.getSessionUserId();
//        if(sessionUserId != null && sessionUserId.equals(userId)) {
//            return diaryService.getDiaryList(userId);
//        }
//        System.out.println("用户未登录，无法访问");
//        LOG.info("-------getDiaryList-----------");
        return diaryService.getDiaryList(userService.getSessionUserId());
    }

    @PostMapping("/add")
    public String addDiary(DiaryDao diary) {
//        LOG.info("----------------addNewDiary------------");
        LOG.info(diary.toString());
        if (diary == null) return "FAILD";
        diary.setUserId(userService.getSessionUserId());
        if (diaryService.addOrUpdate(diary))
            return "SUCCESS";
        return "FAILD";
    }

    @GetMapping("/del/{diaryId}")
    public void deleteDiary(@PathVariable("diaryId") Integer diaryId) {  //待测试
        diaryService.deleteDiary(diaryId);
    }

    @GetMapping("/{diaryId}")
    public DiaryDao getDiaryById(@PathVariable Integer diaryId) {
        DiaryDao diary = null;
        if (diaryId != null)
            diary = diaryService.getDiaryById(diaryId);
        return diary;
    }

    @PostMapping("/update")
    public String updateDiary(DiaryDao diary) {
        LOG.info("updateDiary");
        if (diary == null) return "FAILD";
        diary.setUserId(userService.getSessionUserId());
        if (diaryService.addOrUpdate(diary))
            return "SUCCESS";
        return "FAILD";
    }

}
